package com.sq.partner.manager.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.ActirationErrorInfo;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.ActirationCardDifinition;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NlifePlan;
import com.sq.partner.manager.mybatis.model.Salesarea;
import com.sq.partner.manager.service.ActirationCardService;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
/**
 * 激活卡管理
 * @author liufengdi
 *
 */
@Controller
@RequestMapping(value = "/actirationCard")
public class ActirationCardController {
	
  @Resource
  private ActirationCardService actirationCardService;
  /**
   * 卡模板列表
   * @param request
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/difinition")
  public String difinition(HttpServletRequest request) throws Exception {
    return "actirationCard/difinition/index";
  }
  /**
   * 新增卡模板
   * @param request
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/difinitionAdd")
  public String difinitionAdd(ModelMap model, HttpServletRequest request, String id) throws Exception {
    return "actirationCard/difinition/add";
  }
  /**
   * 激活卡模板分页查询
   * @param session
   * @param page
   * @param actirationCardDifinition 条件信息
   * @return
   * @throws Exception
   */
  @RequestMapping(value = "/queryList", method = RequestMethod.POST)
  @ResponseBody
  public Page<ActirationCardDifinition>  difinitionQueryList(HttpSession session, Page<ActirationCardDifinition> page,ActirationCardDifinition actirationCardDifinition) throws Exception{
    Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
    if(StrUtil.isNotEmpty(actirationCardDifinition.getIsBegin())){
        paramMap.put("isBegin", actirationCardDifinition.getIsBegin());
    }
    if(actirationCardDifinition.getId()!=null){
    // if(StrUtil.isNotEmpty(actirationCardDifinition.getId()+"")){
        paramMap.put("id", actirationCardDifinition.getId());
    }
    if(StrUtil.isNotEmpty(actirationCardDifinition.getName())){
        paramMap.put("name", "%" + actirationCardDifinition.getName() + "%");
    }
    if(StrUtil.isNotEmpty(actirationCardDifinition.getStartTime())){
        paramMap.put("startTime", actirationCardDifinition.getStartTime());
    }
    if(StrUtil.isNotEmpty(actirationCardDifinition.getEndTime())){
        paramMap.put("endTime", actirationCardDifinition.getEndTime());  
    }
    //查询所有分公司数量放入查询
    List<CoreDept> comlist=actirationCardService.queryComcode();
    paramMap.put("comnum",""+comlist.size());
    page.setMap(paramMap);
    page = actirationCardService.queryActirationCardDifinition(page);
    return page;
  }
  /**
	 * 激活卡模板单卡信息查询
	 * @param session
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/query", method = RequestMethod.POST)
	@ResponseBody
	public ActirationCardDifinition difinitionQuery(String templatid) throws Exception{
			return actirationCardService.queryCardTemplate(templatid);
	}
	/**
	 * 新增激活卡信息
	 * @param session
	 * @param actDifinition 卡模板信息
	 * @param salesList 销售区域信息
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST,  produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String difinitionAdd(@RequestParam(required=false) MultipartFile[] imgfile,HttpSession session,ActirationCardDifinition actDifinition) throws Exception{
		byte[] image=null;
		StringBuffer errormes=new StringBuffer();
		for(MultipartFile file : imgfile){
			//根据名称校验文件格式
			String fileNameStr = file.getOriginalFilename();
			int lastDotIndex = fileNameStr.lastIndexOf(".");
			if(-1==lastDotIndex){
			    // lfd 20180919 图片不必传
				// errormes.append(ActirationErrorInfo.DEFINE_IMAGE_1);
			}else{
				String extName = fileNameStr.substring(lastDotIndex+1,fileNameStr.length()).toLowerCase();
				//转换小写,校验格式
				if("bmp".equals(extName)||"jpg".equals(extName)||"png".equals(extName)){
					if (file.isEmpty()) {
						errormes.append(ActirationErrorInfo.DEFINE_IMAGE_2);
					} 
					//文件格式校验通过才转换
					else{
						  InputStream inputStream = file.getInputStream();
						  //转byte[]
						  ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
						  byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据 
						  int rc = 0; 
						  while ((rc = inputStream.read(buff, 0, 100)) > 0) { 
						  swapStream.write(buff, 0, rc); 
						} 
						image = swapStream.toByteArray();
					}
				}else{
					errormes.append(ActirationErrorInfo.DEFINE_IMAGE_3);
				}
			}
			
		}
		// lfd 20180919 图片不必传
		/* if(null==image){
			return Result.error(errormes.toString());
		} */
		//放入对象
		actDifinition.setImage(image);
		//校验铭板名称唯一，模板名称唯一索引
		Integer i=actirationCardService.queryDefineNameCount(actDifinition.getName());
		//查询该激活卡定义中关联的产品固定保费（检验激活卡的总保费和固定保费一致）
		BigDecimal planAmount=actirationCardService.queryAllpremium(actDifinition.getPlanNo());
		//转成json串 lfd added 20181031
		ObjectMapper mapper=new ObjectMapper();
		if(i>0){
		    return mapper.writeValueAsString(Result.error(ActirationErrorInfo.DEFINE_CARD_1));
		}else if(0!=planAmount.compareTo(actDifinition.getModalPremamtPp())){
		    //保费与方案总保费不等
		    return mapper.writeValueAsString(Result.error(ActirationErrorInfo.DEFINE_CARD_19+planAmount));
		}
		else{
			GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
			String deptNo=gatewayuser.getUserComcode();
			actDifinition.setEmpno(gatewayuser.getUserCode());
			actDifinition.setDefineDeptno(deptNo);
			actDifinition.setDefineDate(new Date());
			//开始插入
			boolean flag=actirationCardService.insertCardTemplate(session,actDifinition);
			//判断是否插入成功
			if(flag){
			    return mapper.writeValueAsString(Result.success(ActirationErrorInfo.DEFINE_CARD_SUCCESS));
			}else{
			    return mapper.writeValueAsString(Result.error(ActirationErrorInfo.DEFINE_CARD_3));
			}
		}
	}
	/**
	 * 单条修改激活卡信息
	 * @param session
	 * @param actDifinition
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST,  produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String difinitionUpdate(@RequestParam(required=false) MultipartFile[] imgfile,HttpSession session,ActirationCardDifinition actDifinition) throws Exception{
		byte[] image=null;
		StringBuffer errormes=new StringBuffer();
        //转成json串 lfd added 20181031
        ObjectMapper mapper=new ObjectMapper();
		for(MultipartFile file : imgfile){
			//根据名称校验文件格式
			String fileNameStr = file.getOriginalFilename();
			int lastDotIndex = fileNameStr.lastIndexOf(".");
			if(-1==lastDotIndex){
				//errormes.append(ActirationErrorInfo.DEFINE_IMAGE_1);
				//未传图片时
				image=null;
			}else{
				String extName = fileNameStr.substring(lastDotIndex+1,fileNameStr.length()).toLowerCase();
				//转换小写,校验格式
				if("bmp".equals(extName)||"jpg".equals(extName)||"png".equals(extName)){
					if (file.isEmpty()) {
						errormes.append(ActirationErrorInfo.DEFINE_IMAGE_2);
					} 
					//文件格式校验通过才转换
					else{
						  InputStream inputStream = file.getInputStream();
						  //转byte[]
						  ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); 
						  byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据 
						  int rc = 0; 
						  while ((rc = inputStream.read(buff, 0, 100)) > 0) { 
						  swapStream.write(buff, 0, rc); 
						} 
						image = swapStream.toByteArray();
					}
				}else{
					errormes.append(ActirationErrorInfo.DEFINE_IMAGE_3);
				}
			}
			
		}
		if(null==image){
			actDifinition.setImage(null);//return Result.error(errormes.toString());
		}else{
			//放入对象
			actDifinition.setImage(image);
		}
		//开始修改
		boolean flag=actirationCardService.updateCardTemplate(actDifinition);
		if(flag){
		    return mapper.writeValueAsString(Result.success(ActirationErrorInfo.DEFINE_CARD_5));
		}else{
		    return mapper.writeValueAsString(Result.error(ActirationErrorInfo.DEFINE_CARD_6));
		}
	}

	/**
	 * 根据主键删除激活卡信息
	 * @param session
	 * @param actDifinition
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public Result difinitionDelete(String templatid) throws Exception{
		if(StrUtil.isNotEmpty(templatid)){
			boolean flag=actirationCardService.deleteCardTemplate(templatid);
			if(flag){
				return Result.success(ActirationErrorInfo.DEFINE_CARD_8);
			}else{
				return Result.error(ActirationErrorInfo.DEFINE_CARD_9);
			}
		}else{
			return Result.error(ActirationErrorInfo.DEFINE_CARD_10);
		}
		
	}
	/**
	 * 激活卡模板启动停用
	 * @param templatid
	 * @param onoffflag 1启用0停用
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/onoff", method = RequestMethod.POST)
	@ResponseBody
	public Result changeOnOff(String templatid,String onoffflag) throws Exception{
		if(StrUtil.isNotEmpty(templatid)&&StrUtil.isNotEmpty(onoffflag)){
			boolean falg=actirationCardService.chageYN(templatid,onoffflag);
			if(falg){
				return Result.success(ActirationErrorInfo.DEFINE_CARD_11);
			}else{
				return Result.error(ActirationErrorInfo.DEFINE_CARD_12);
			}
		}else{
			return Result.error(ActirationErrorInfo.DEFINE_CARD_13);
		}
	}
	
	/**
	 * 绑定销售区域
	 * @param sales
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/binding", method = RequestMethod.POST)
	@ResponseBody
	public Result boundArea(@RequestParam String salesId,@RequestParam List<String> salesList) throws Exception {
		boolean flag=actirationCardService.boundArea(salesId,salesList);
		if(flag){
			return Result.success(ActirationErrorInfo.DEFINE_CARD_14);
		}else{
			return Result.error(ActirationErrorInfo.DEFINE_CARD_15);
		}
	}
	/**
	 * 查询绑定信息
	 * @param sales
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querybind", method = RequestMethod.POST)
	@ResponseBody
	public List<Salesarea> querybound(Salesarea sales) throws Exception {
		return actirationCardService.querybound(sales);
	}
	/**
	 * 删除绑定信息
	 * @param sales
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/removebind", method = RequestMethod.POST)
	@ResponseBody
	public Result removebound(Salesarea sales) throws Exception {
		if(null!=sales&&StrUtil.isNotEmpty(sales.getDeptNo())&&null!=sales.getCardDefineId()){
			boolean flag=actirationCardService.deletebound(sales);
		    if(flag){
		    	return Result.success(ActirationErrorInfo.DEFINE_CARD_16);
		    }else{
		    	return Result.error(ActirationErrorInfo.DEFINE_CARD_17);
		    }
		}else{
			return Result.error(ActirationErrorInfo.DEFINE_CARD_13);
		}
	}
	/**
	 * 查询所有分公司，需要绑定的机构
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/querycomcode", method = RequestMethod.POST)
	@ResponseBody
	public List<CoreDept> queryComcode() throws Exception {
		return actirationCardService.queryComcode();
	}
	
	/**
	 * 分页条件查询方案
	 * @param session
	 * @param page
	 * @param nlifePlan
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryNlifePlanPageByCriteriaForCard")
	@ResponseBody
	public Page<NlifePlan> queryNlifePlanPageByCriteria(Page<NlifePlan> page,NlifePlan nlifePlan) throws Exception{
		Map<String,Object> paramMap = SqlUtil.buildPageMap(page);
		paramMap.put("state", "1");
		paramMap.put("agentType","7");
		if(StrUtil.isNotEmpty(nlifePlan.getPlanNo())){
			paramMap.put("planNo", nlifePlan.getPlanNo());
		}
		if(StrUtil.isNotEmpty(nlifePlan.getPlanName())){
			paramMap.put("planName", nlifePlan.getPlanName());
		}
		page.setMap(paramMap);
		page = actirationCardService.queryNlifePlanPageByCriteria(page);
		return page;
	}
	
}
